import React, { useState, useEffect, useMemo } from'react';
import { useLocation } from'react-router-dom';
import { asyncGetAppProfile, asyncAppAuthentication, asyncGetProfile } from '@/api/common';
import PcChat from "./pc/index.jsx";
import EmbedChat from "./embed/index.jsx";
import BaseChat from "./base/index.jsx";

const ChatComponent = () => {
    const location = useLocation();
    const query = new URLSearchParams(location.search);
    const mode = query.get('mode');
    const accessToken = location.pathname.split('/').pop(); // 假设 accessToken 在路径末尾

    const [isAuth, setIsAuth] = useState(false);
    const [loading, setLoading] = useState(false);
    const [showHistory, setShowHistory] = useState(false);
    const [applicationProfile, setApplicationProfile] = useState({});
    const [initDataEnd, setInitDataEnd] = useState(false);
    const [applicationAvailable, setApplicationAvailable] = useState(true);

    const currentTemplate = useMemo(() => {
        let modeName = '';
        if (mode && mode === 'embed') {
            modeName = 'embed';
        } else {
            modeName = showHistory ||!window.user.isEnterprise()? 'pc' : 'base';
        }
        return modeName;
    }, [mode, showHistory]);

    const chatShow = useMemo(() => {
        if (initDataEnd) {
            if (!applicationAvailable) {
                return true;
            }
            if (applicationProfile) {
                if (applicationProfile.authentication && isAuth) {
                    return true;
                } else if (!applicationProfile.authentication) {
                    return true;
                }
            }
        }
        return false;
    }, [initDataEnd, applicationAvailable, applicationProfile, isAuth]);

    const getAppProfile = async () => {
        try {
            const res = await asyncGetAppProfile(setLoading);
            setShowHistory(res.data?.show_history);
            setApplicationProfile(res.data);
        } catch (error) {
            console.error('Error getting app profile:', error);
        }
    };

    const getAccessToken = async (token) => {
        try {
            await asyncAppAuthentication(token, setLoading);
            await getAppProfile();
        } catch (error) {
            console.error('Error authenticating app:', error);
        }
    };

    useEffect(() => {
        window.user.changeUserType(2);
        Promise.all([asyncGetProfile(), getAccessToken(accessToken)])
          .catch(() => {
                setApplicationAvailable(false);
            })
          .finally(() => setInitDataEnd(true));
    }, [accessToken]);

    return (
        <div>
            {chatShow && initDataEnd && (
                <>
                    {currentTemplate === 'pc' && (
                        <PcChat
                            applicationAvailable={applicationAvailable}
                            application_profile={applicationProfile}
                        />
                    )}
                    {currentTemplate === 'embed' && (
                        <EmbedChat
                            applicationAvailable={applicationAvailable}
                            application_profile={applicationProfile}
                        />
                    )}
                    {currentTemplate === 'base' && (
                        <BaseChat
                            applicationAvailable={applicationAvailable}
                            application_profile={applicationProfile}
                        />
                    )}
                </>
            )}
        </div>
    );
};

export default ChatComponent;